package edu.zcmu.seckill.controller;


import com.auth0.jwt.interfaces.DecodedJWT;
import edu.zcmu.seckill.entity.SeckillProduct;
import edu.zcmu.seckill.exception.MyException;
import edu.zcmu.seckill.response.R;
import edu.zcmu.seckill.response.ResultCode;
import edu.zcmu.seckill.service.AdminService;
import edu.zcmu.seckill.service.ProductService;
import edu.zcmu.seckill.service.SeckillProductPolicyService;
import edu.zcmu.seckill.utils.JwtUtil;
import edu.zcmu.seckill.vo.AddFromVo;
import edu.zcmu.seckill.vo.AdminLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 唐诗
 * @since 2022-04-16
 */
@RestController
@RequestMapping("/admin/seckill/admin")
public class AdminController {

    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    ProductService productService;
    @Autowired
    AdminService adminService;
    @Autowired
    SeckillProductPolicyService seckillProductPolicyService;
    @PostMapping("/login")
    public R login(@RequestBody AdminLoginVo loginVo){
        R r=adminService.login(loginVo);
        return r;
    }

    @GetMapping("/getSeckillProduct")
    public R getAllProductInfo(HttpServletRequest request){
        R r=adminService.getSeckillProduct(request);
        return r;
    }

    @GetMapping("/getNormalProduct")
    public R getNormalProduct(HttpServletRequest request){
        R r=adminService.getNormalProduct(request);
        return r;
    }

    @PostMapping("/addSeckillProduct")
    public R addSeckillProduct(@RequestBody @Valid AddFromVo addFromVo, HttpServletRequest request, BindingResult result){
        if (result.hasErrors()){
            return R.error().message(result.getFieldError().getDefaultMessage());
        }
        R r=adminService.addSeckillProduct(addFromVo,request);
        return r;
    }

    @GetMapping("/delSeckillProduct")
    public R delSeckillProduct(@RequestParam("id") Integer id,HttpServletRequest request){
        R r=adminService.delSeckillProduct(id,request);

        return r;
    }

    @DeleteMapping("/delProduct/{id}")
    public R delProduct(@PathVariable("id") Integer id,HttpServletRequest request){
        DecodedJWT tokenInfo = JwtUtil.getTokenInfo(request.getHeader("atoken"));
        String name = tokenInfo.getClaim("name").asString();
        if (StringUtils.isEmpty(name)){
            throw new MyException(ResultCode.ERROR,"管理员信息异常");
        }
        boolean b = productService.removeById(id);
        return R.ok().data("data",b);
    }
}
